package logic

import (
	"bole/bokerpc/bokerpc"
	"bole/bokerpc/internal/svc"
	"bole/models/cache"
	"bole/models/mysql"
	"bole/pkg"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *bokerpc.LoginRequest) (*bokerpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var finduser mysql.Boke
	if finduser.ID == 0 {
		return nil, fmt.Errorf("用户不存在,请前去注册")
	}
	if finduser.Mobile != "" {
		mysql.DB.Debug().Where("mobile =?", in.Mobile).Find(&finduser)
		if finduser.ID == 0 {
			return nil, fmt.Errorf("用户不存在,请前去注册")
		}
		result1, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
		if result1 != in.CaptchaCode {
			return nil, fmt.Errorf("手机号验证码,获取失败")
		}
	}
	if finduser.Account != "" {
		mysql.DB.Debug().Where("account =?", in.Account).Find(&finduser)

		result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
		if result != in.CaptchaCode {
			return nil, fmt.Errorf("图形验证码,获取失败")
		}
		if pkg.Md5(in.Password) != finduser.Password {
			return nil, fmt.Errorf("密码错误,请重新输入")
		}
	}
	return &bokerpc.LoginResponse{
		Userid: int64(finduser.ID),
	}, nil
}
